package com.ruoyi.system.ali;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.ruoyi.common.enums.ChannelEnum;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.common.utils.file.AliOss;
import com.ruoyi.common.utils.sign.SignMD5Util;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.ZfbConfig;
import com.ruoyi.system.dto.ApiByPhoneAddDto;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ZfbConfigService;
import com.ruoyi.system.vo.ApiPayResultVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.TreeMap;

/**
 * 当面付
 */
@Component
public class FacePayService implements ChannelService {


    @Resource
    ISysConfigService configService;
    private static final String serverUrl = "https://openapi.alipay.com/gateway.do";
    @Resource
    private ZfbConfigService zfbConfigService;

    @Override
    public String getType() {
        return ChannelEnum.FACE.getCode();
    }

    //当面付
    @Override
    public Object create(AliPayDto aliPayDto, Order order) {
        aliPayDto.setNotifyUtl(configService.selectConfigByKey("zfbNotifyUtl") + "/api/order/notify");

        order.setChannelName(ChannelEnum.FACE.getName());
        order.setType("auto");

        //将链接解析成二维码
        String qrCode =getqrCode(aliPayDto,order);
        QrConfig qrConfig = new QrConfig();
        qrConfig.setWidth(200);
        qrConfig.setHeight(200);
        byte[] bytes = QrCodeUtil.generatePng(qrCode, qrConfig);
        String projectName = configService.selectConfigByKey("projectName");
        String picUrl = AliOss.uploadToOss(bytes, projectName + "/orderReceive/" + aliPayDto.getOrderNo() + ".jpg");

        AliPayVo aliPayVo = new AliPayVo();
        aliPayVo.setOrderNo(aliPayDto.getOrderNo());
        aliPayVo.setAmount(aliPayDto.getAmount());
        aliPayVo.setPic(picUrl);
        aliPayVo.setQrCode(qrCode);
        order.setPic(aliPayVo.getPic());
        order.setZfbUrl(aliPayVo.getQrCode());


//        ApiPayResultVo apiVo = new ApiPayResultVo();
//        apiVo.setAmount(String.valueOf(order.getAmount()));
//        apiVo.setOrderNo(order.getOrderNo());
//        apiVo.setMerchantId(order.getMerchantId());
//        TreeMap<String, String> map = SignMD5Util.objToMap(apiVo);
//        String sign = SignMD5Util.getSign(map, "sign");
//        String payUrl = configService.selectConfigByKey("payUrl");
//        payUrl = payUrl + "?" + SignMD5Util.getStr(map, sign);
//        apiVo.setUrl(payUrl);
        ApiPayResultVo apiVo = new ApiPayResultVo();
        apiVo.setAmount(String.valueOf(order.getAmount()));
        apiVo.setOrderNo(order.getOrderNo());
        apiVo.setMerchantId(order.getMerchantId());
        TreeMap<String, String> map = SignMD5Util.objToMap(apiVo);
        map.put("payType", "1");
        String sign = SignMD5Util.getSign(map, "sign");
        String payUrl = configService.selectConfigByKey("template");
        payUrl = payUrl + "?" + SignMD5Util.getStr(map, sign);
        apiVo.setUrl(payUrl);
        return apiVo;
    }

    private String getqrCode(AliPayDto aliPayDto, Order order) {
        ZfbConfig config = zfbConfigService.getChannelConfig(this.getType());
        order.setAccount(config.getAccount());
        String publicKey = config.getAlipayPublicKey();
        String privateKey = config.getPrivateKey();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, config.getAppId(), privateKey, "json", "GBK", publicKey, "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(aliPayDto.getNotifyUtl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", aliPayDto.getOrderNo());
        bizContent.put("total_amount", aliPayDto.getAmount());
        bizContent.put("subject", "线下商品");
        //// 扩展信息，按需传入
        JSONObject extendParams = new JSONObject();
//        extendParams.put("sys_service_provider_id", "2088602262610814");
        bizContent.put("extend_params", extendParams);
        request.setBizContent(bizContent.toString());

        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (Exception e) {

            throw new BusiException("渠道发生错误");
        }

        if (!response.isSuccess()) {
            throw new BusiException(response.getSubMsg());
        }
        //将链接解析成二维码
        String qrCode = response.getQrCode();

        return qrCode;
    }

    @Override
    public AliPayVo createByPhone(ApiByPhoneAddDto apiByPhoneAddDto, Order order) {
        return null;
    }


}
